package cn.enjoy.socket.tcp;

import java.io.*;
import java.net.Socket;

/**
 * @author K
 * @date 2024-06-04 20:36
 * 文件上传客户端（上传文件到客户端）
 **/
public class TCPUploadFileClient {
    public static void main(String[] args) {
        try {
            //创建Socket，并连接到指定的服务器
            Socket socket = new Socket("192.168.0.100", 10086);

            //获取项目下指定文件的路径资源流（file/testUser/jdk.zip需要提前在resources资源目录下定义好）
            //发送jdk.zip给服务端
            InputStream inputStream = TCPUploadFileClient.class
                    .getResourceAsStream("/file/testUser/jdk.zip");
            //获取Socket的网络流（输出）
            OutputStream outputStream = socket.getOutputStream();

            //写出jdk.zip数据发送到客户端
            byte[] bytes = new byte[1024];
            int index = 0;
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
            }
            //告知服务端写出数据结束
            socket.shutdownOutput();

            //接收服务端返回来的信息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("服务端返回：" + bufferedReader.readLine());
            socket.shutdownInput();

            //关闭Socket还得关闭我们自己创建的流
            socket.close();
            inputStream.close();
            bufferedReader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}